package com.qdxwx.data.service.manager;

import com.qdxwx.common.exception.BusinessException;
import com.qdxwx.common.page.PageRequest;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.mapper.manager.ManagerRoleMapper;
import com.qdxwx.data.mapper.manager.RoleMapper;
import com.qdxwx.data.mapper.manager.RoleMenuMapper;
import com.qdxwx.models.manager.ManagerRole;
import com.qdxwx.models.manager.Role;
import com.qdxwx.models.manager.RoleMenu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 角色 业务层处理
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Autowired
    private ManagerRoleMapper managerRoleMapper;


    /**
     * 根据条件分页查询角色数据
     *
     * @param role 角色信息
     * @return 角色数据集合信息
     */
    @Override
    public List<Role> getList(Role role, PageRequest page) {
        return roleMapper.selectList(role, page);
    }

    @Override
    public int count(Role role) {
        return roleMapper.selectCount(role);
    }

    /**
     * 根据用户ID查询权限
     *
     * @param managerId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> getKeys(int managerId) {
        List<Role> perms = roleMapper.selectRolesByManagerId(managerId);
        Set<String> permsSet = new HashSet<>();
        for (Role perm : perms) {
            if ((null != perm)) {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }


    /**
     * 通过角色ID查询角色
     *
     * @param roleId 角色ID
     * @return 角色对象信息
     */
    @Override
    public Role get(Integer roleId) {
        return roleMapper.selectRoleById(roleId);
    }

    /**
     * 批量删除角色信息
     *
     * @param ids 需要删除的数据ID
     * @throws Exception
     */
    @Override
    public int deleteByIds(String ids) throws BusinessException {
        Integer[] roleIds = TKConvert.toIntArray(ids);
        for (Integer roleId : roleIds) {
            checkRoleAllowed(new Role(roleId));
            Role role = get(roleId);
            if (countUserRoleByRoleId(roleId) > 0) {
                throw new BusinessException(String.format("%1$s已分配,不能删除", role.getRoleName()));
            }
        }
        return roleMapper.deleteRoleByIds(roleIds);
    }

    @Override
    @Transactional
    public int insert(Role role) {
        role.setCreateTime(LocalDateTime.now());
        role.setUpdateTime(LocalDateTime.now());
        int row = roleMapper.insertRole(role);
        if(row > 0){
            insertRoleMenu(role);
        }
        return row;
    }

    @Override
    @Transactional
    public int update(Role role) {
        role.setUpdateTime(LocalDateTime.now());
        int row = roleMapper.updateRole(role);
        if(row > 0){
            roleMenuMapper.deleteByRoleId(role.getRoleId());
            insertRoleMenu(role);
        }
        return row;
    }

    public int insertRoleMenu(Role role) {
        int rows = 1;
        // 新增用户与角色管理
        List<RoleMenu> list = new ArrayList<>();
        for (Integer menuId : role.getMenuIds()) {
            RoleMenu rm = new RoleMenu();
            rm.setRoleId(role.getRoleId());
            rm.setMenuId(menuId);
            list.add(rm);
        }
        if (list.size() > 0) {
            rows = roleMenuMapper.batchRoleMenu(list);
        }
        return rows;
    }

    @Override
    public boolean checkRoleName(String roleName) {
        if (TKString.isEmpty(roleName)) return false;
        return roleMapper.checkRoleName(roleName) > 0;
    }

    @Override
    public boolean checkRoleKey(String roleKey) {
        if (TKString.isEmpty(roleKey)) return false;
        return roleMapper.checkRoleKey(roleKey) > 0;
    }

    @Override
    public void checkRoleAllowed(Role role) {
        if ((null != role.getRoleId()) && role.isAdmin()) {
            throw new BusinessException("不允许操作超级管理员角色");
        }
    }

    @Override
    public int countUserRoleByRoleId(Integer roleId) {
        return managerRoleMapper.countManagerRoleByRoleId(roleId);
    }

    @Override
    public int updateStatus(Role role) {
        return roleMapper.updateRole(role);
    }

    @Override
    public int deleteAuthManager(ManagerRole managerRole) {
        return managerRoleMapper.deleteManagerRoleInfo(managerRole);
    }

    @Override
    public int deleteAuthManagers(Integer roleId, Integer[] managerIds) {
        return managerRoleMapper.deleteManagerRoleInfos(roleId, managerIds);
    }

    @Override
    public int insertAuthManagers(Integer roleId, Integer[] managerIds) {
        // 新增用户与角色管理
        List<ManagerRole> list = new ArrayList<>();
        for (int managerId : managerIds) {
            ManagerRole ur = new ManagerRole();
            ur.setManagerId(managerId);
            ur.setRoleId(roleId);
            list.add(ur);
        }
        return managerRoleMapper.batchManagerRole(list);
    }


}
